package com.hee.erp.modules.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/modules/file")
@Api(tags = "FileController", produces = "text/html")
public class FileController {

    //绑定文件上传路径到uploadPath
    @Value("${web.upload-path}")
    private String uploadPath;
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy-MM-dd/");

    @ApiOperation(value = "upload")
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile uploadFile, HttpServletRequest request) throws IOException {
        // 在 uploadPath 文件夹中通过日期对上传的文件归类保存
        // 比如：/2019/06/06/cf13891e-4b95-4000-81eb-b6d70ae44930.png
        String format = sdf.format(new Date());
        File folder = new File(uploadPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        // 对上传的文件重命名，避免文件重名
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."));
        // 文件保存
        uploadFile.transferTo(new File(folder, newName));
        // 返回上传文件的访问路径
        String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + format + newName;
        return filePath;
    }

    @ApiOperation(value = "download")
    @PostMapping("/download")
    public void download(@RequestBody Map params, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //取出文件在硬盘上的相对路径
        String url = params.get("url").toString();
        System.out.println(url);
        int index = url.indexOf(request.getContextPath());
        String fileRelativePath = url.substring(index + request.getContextPath().length() + 1);
        //拼接文件的绝对路径
        String fileAbsolutePath = this.uploadPath + fileRelativePath;
        File file = new File(fileAbsolutePath);
        int indexFileName = fileRelativePath.lastIndexOf("/") + 1;
        String fileName = fileRelativePath.substring(indexFileName);
        if (file.exists()) {
            //获取文件名
            //本地硬盘存在
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);

            byte[] buffer = new byte[1024];
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);

            OutputStream os = response.getOutputStream();

            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            bis.close();
            fis.close();

        } else {

            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName=" + System.currentTimeMillis() + ".jpg");

            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, byte[].class);
            byte[] buffer = responseEntity.getBody();

            OutputStream os = response.getOutputStream();
            os.write(buffer);

        }
    }
}
